package com.hmall.user.web;

import com.hmall.user.dto.LoginDto;
import com.hmall.user.dto.UserDto;
import com.hmall.user.service.UserService;
import com.hmall.user.vo.LoginVo;
import com.hmall.utils.SMSUtils;
import com.hmall.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

import java.util.concurrent.TimeUnit;


@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private SMSUtils smsUtils;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 添加一个方法，处理前端的登录请求/user/login
     *
     * @param dto
     * @return
     */
    @PostMapping("/login")
    public LoginVo login(@RequestBody LoginDto dto) {
        return userService.queryListByName(dto);
    }

    /**
     * 添加一个方法，处理前端的注册请求/user/register
     *
     * @param dto
     * @return
     */
    @PostMapping("/register")
    public void register(@RequestBody UserDto dto) throws Exception {
        userService.addUser(dto);
    }

    /**
     * 验证用户名/手机号是否存在
     *
     * @param value
     * @param type  (1:用户名，2:手机号)
     */
    @GetMapping("/check/{value}/{type}")
    public ResponseEntity<Boolean> checkUserExists(@PathVariable String value, @PathVariable String type) {
        boolean exists = false;
        if ("1".equals(type)) {
            exists = userService.checkUserName(value);
        } else if ("2".equals(type)) {
            exists = userService.checkPhone(value);
        } else {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "无效的类型");
        }
        return ResponseEntity.ok(exists);
    }

    /**
     * 发送手机短信验证码
     *
     * @param phone
     * @return
     */
    @PostMapping("/code")
    public ResponseEntity<String> sendMsg(@RequestParam("phone") String phone) {
        //判断手机号是否为空
        if (phone != null && !phone.isEmpty()) {
            //生成随机的4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            //保存验证码到Redis,时效性为5分钟
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            //获取Redis中的验证码
            String redisKv = redisTemplate.opsForValue().getAndSet(phone, code);
            if (redisKv != null) {
                log.info("Redis中的验证码: " + redisKv);
            }
            // 模拟发送验证码到手机（控制台）
            log.info("======短信验证码为：" + code);
            //判断验证码是否为空（如果错误，抛异常）
            if (code == null || code.isEmpty()) {
                throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "验证码为空");
            }
            //调用阿里云提供的短信服务API完成发送短信
            smsUtils.sendMessage("阿里云短信测试", "SMS_154950909", phone, code);
            //返回验证码
            return new ResponseEntity<String>(code, HttpStatus.OK);
        }
        return new ResponseEntity<String>("手机号为空", HttpStatus.BAD_REQUEST);
    }
}